package com.winhc.net.dao;

import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.winhc.net.db.mybatis.dataobject.WebsiteContent;
import com.winhc.net.db.mybatis.dataobject.WebsiteContentExample;
import com.winhc.net.db.mybatis.mapper.WebsiteContentMapper;
import com.winhc.net.dto.QueryContentRequest;
import com.winhc.net.dto.RequestDTO;
import com.winhc.net.dto.ResponseDTO;
import com.winhc.net.dto.ResponseGen;

@Service
public class ContentDao {
    private static Log log = LogFactory.getLog(ContentDao.class);

    @Autowired
    WebsiteContentMapper websiteContentMapper;

    public ResponseDTO queryContent(RequestDTO header, QueryContentRequest queryContentRequest) {

        Page<?> page = null;
        if (header != null && StringUtils.isNotEmpty(header.getPageNum())
                && StringUtils.isNotEmpty(header.getPageSize())) {
            page = PageHelper.startPage(Integer.parseInt(header.getPageNum()),
                    Integer.parseInt(header.getPageSize()), true);
            log.info("获取分页信息" + JSON.toJSONString(page));
        }

        WebsiteContentExample example = new WebsiteContentExample();
        WebsiteContentExample.Criteria criteria = example.createCriteria();
        if (queryContentRequest.getCategoryId() != null) {
            criteria.andStatusEqualTo("1");
            criteria.andCategoryIdEqualTo(Long.parseLong(queryContentRequest.getCategoryId()));

        }
        if (queryContentRequest.getContentId() != null) {
            criteria.andIdEqualTo(Long.parseLong(queryContentRequest.getContentId()));
        }
        example.setOrderByClause("created desc");
        List<WebsiteContent> list = websiteContentMapper.selectByExampleWithBLOBs(example);
        ResponseDTO responseDTO = ResponseGen.genResult(list);
        if (page != null) {
            log.info("获取分页信息" + JSON.toJSONString(page));
            responseDTO.setPageNum(page.getPageNum() + "");
            responseDTO.setPageSize(page.getPageSize() + "");
        }

        log.info("responseDTO--------------" + responseDTO);
        return responseDTO;
    }
    
    public int saveContent(WebsiteContent content) {
    		return websiteContentMapper.insertSelective(content);
    }
    
    public int updateContent(WebsiteContent content) {
    		return websiteContentMapper.updateByPrimaryKeySelective(content);
    }
    
    
    public int delContent(Long id) {
		return websiteContentMapper.deleteByPrimaryKey(id);
    }
    
}
